package com.cangjie.xiaozhi

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.wm.ToolWindowManager

class SendToXiaoZhiAction : AnAction() {
    override fun actionPerformed(e: AnActionEvent) {
        val project = e.project ?: return
        val editor = e.getData(CommonDataKeys.EDITOR)
        val selectedText = getSelectedTextOrLine(editor)
        
        if (selectedText.isNullOrEmpty()) {
            Messages.showMessageDialog(
                project,
                "未找到要发送给仓颉小智的代码",
                "无代码内容",
                Messages.getInformationIcon()
            )
            return
        }
        
        // 调试信息
        println("准备发送的代码: $selectedText")
        
        // 获取tool window服务实例
        val toolWindowService = XiaozhiToolWindowService.getInstance()
        var toolWindow = toolWindowService.getToolWindow()
        
        // 显示tool window
        val toolWindowManager = ToolWindowManager.getInstance(project)
        val window = toolWindowManager.getToolWindow("仓颉小智")
        
        if (window == null) {
            Messages.showMessageDialog(
                project,
                "未找到 仓颉小智 ToolWindow",
                "ToolWindow 错误",
                Messages.getErrorIcon()
            )
            return
        }
        
        window.show()
        
        // 等待toolWindow初始化完成
        if (toolWindow == null) {
            // 等待一小段时间确保ToolWindow初始化完成
            try {
                Thread.sleep(100)
            } catch (e: InterruptedException) {
                // 忽略中断异常
            }
            toolWindow = toolWindowService.getToolWindow()
        }
        
        // 等待页面加载完成后再发送消息
        if (toolWindow != null) {
            println("开始等待页面加载完成...")
            val loaded = toolWindow.waitForPageLoad()
            println("页面加载完成状态: $loaded")
            
            if (!loaded) {
                // 即使超时也继续发送消息，因为页面可能已经部分加载
                Messages.showMessageDialog(
                    project,
                    "页面加载可能未完成，但仍会尝试发送代码",
                    "加载提醒",
                    Messages.getWarningIcon()
                )
            }
            
            // 发送选中的代码到浏览器编辑器
            println("开始发送代码到编辑器...")
            toolWindowService.sendMessageToXiaoZhi(selectedText)
            println("代码发送完成")
        } else {
            println("ToolWindow 为空，无法发送消息")
            Messages.showMessageDialog(
                project,
                "ToolWindow 初始化失败",
                "初始化错误",
                Messages.getErrorIcon()
            )
        }
    }
    
    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        e.presentation.isEnabledAndVisible = editor != null
    }
    
    private fun getSelectedTextOrLine(editor: Editor?): String? {
        if (editor == null) return null
        
        // 首先尝试获取选中的文本
        val selectedText = editor.selectionModel.selectedText
        if (!selectedText.isNullOrEmpty()) {
            println("获取到选中文本: $selectedText")
            return selectedText.trim()
        }
        
        // 如果没有选中文本，则获取光标所在行的文本
        val caretModel = editor.caretModel
        val logicalPosition = caretModel.logicalPosition
        val line = logicalPosition.line
        
        // 确保行号有效
        if (line >= 0 && line < editor.document.lineCount) {
            val startOffset = editor.document.getLineStartOffset(line)
            val endOffset = editor.document.getLineEndOffset(line)
            val lineText = editor.document.getText().substring(startOffset, endOffset)
            println("获取到整行文本: $lineText")
            return lineText.trim()
        }
        
        return null
    }
}